import React from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Button, Image} from '@tarojs/components';
import {AtModal, AtModalContent, AtBadge} from 'taro-ui';

import * as T from '../../types';
import actions from '../../actions/index';
import {store2Props} from '../../selectors';
import classNames from 'classnames';

import {
  // OSS_PATH_PREFIX,
  // OSS_BASE_PATH_PREFIX,
  RESULT_TYPE,
  GAME_RPICE_TYPE,
  IMAGE_EMPTY,
  PRIZE_STATUS,
  CODE_SUCCESS,
} from '../../constant';

type IInfoProps = T.IProps & T.IInfoProps;

import './ResultModal.less';
import 'taro-ui/dist/style/components/modal.scss';
import 'taro-ui/dist/style/components/flex.scss';
import 'taro-ui/dist/style/components/badge.scss';

// @ts-ignore
@connect<Partial<IInfoProps>, T.IInfoState>(store2Props, actions)
/**
 * 结果模态框
 */
export default class ResultModal extends React.Component<Partial<IInfoProps>, T.IInfoState> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      OPERATES: [
        {
          label: '退出游戏',
          func: 'handleGameOver',
          className: 'left',
        },
        {
          label: '再来一次',
          func: 'handlePlayAgain',
          className: 'left',
        },
        {
          label: '领取奖励',
          func: 'handleReceiveGift',
          className: 'right',
        },
      ],
      atModal: {
        closeOnClickOverlay: false,
      },

      // 角标配置
      badge: {
        max: 99,
      },
    };
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    // 领取奖励
    if (nextProps.main.status.claimingRewards == false && this.props.main.status.claimingRewards == true) {
      console.log('resultModal componentWillReceiveProps 领取奖励');
      if (nextProps.main.response.claimRewards == CODE_SUCCESS) {
        console.log('resultModal componentWillReceiveProps 领取奖励成功');
        // 跳转页面
        Taro.navigateTo({
          url: RESULT_TYPE[GAME_RPICE_TYPE['product']].url + '?prizeStatus=' + PRIZE_STATUS['RECEIVED'],
        });
        // 关闭模态框
        this.props.onCancel();
      } else {
        Taro.showToast({
          title: '领取奖励失败',
          icon: 'none',
        });
      }
    }
  }

  /**
   * 再来一次 （只有奖品需要自己去收藏柜里领，其他都是抽到自动发放）
   */
  handlePlayAgain = () => {
    // 重新刷新页面
    this.props.onPlayAgain();
  };

  /**
   * 领取奖励 （先关闭模态框，抽到任何东西都调用接口归到用户名下）
   */
  handleReceiveGift = () => {
    const {
      main: {gameLotteries},
    } = this.props;

    if (gameLotteries.length == 1) {
      let gameResult = gameLotteries[0];
      let currentResult = RESULT_TYPE[gameResult.prizeType];
      if (currentResult.url) {
        // 点击则自动领取奖励了
        if (gameResult.prizeType == GAME_RPICE_TYPE['product']) {
          this.handleClaimRewards();
        } else {
          Taro.navigateTo({
            url: currentResult.url,
          });
          this.props.onCancel();
        }
      }
    }

    // 批量
    else {
      let index = gameLotteries.findIndex((i) => i.prizeType == GAME_RPICE_TYPE['product']);
      if (index > -1) {
        this.handleClaimRewards();
      } else {
        // 优惠券
        let index = gameLotteries.findIndex((i) => i.prizeType == GAME_RPICE_TYPE['ticket']);
        if (index > -1) {
          Taro.navigateTo({
            url: RESULT_TYPE[GAME_RPICE_TYPE['ticket']].url,
          });
          this.props.onCancel();
        }

        // 道具
        else {
          let index = gameLotteries.findIndex((i) => i.prizeType == GAME_RPICE_TYPE['prop']);
          if (index > -1) {
            Taro.navigateTo({
              url: RESULT_TYPE[GAME_RPICE_TYPE['prop']].url + '?prizeType=2',
            });
            this.props.onCancel();
          }
        }
      }
    }
  };

  /**
   * 自动领取
   */
  handleClaimRewards = () => {
    let {
      main: {gameLotteries},
    } = this.props;
    console.log('resultModal handleClaimRewards game gameLotteries', gameLotteries);

    let result = gameLotteries.filter((i) => i.prizeType == GAME_RPICE_TYPE['product']);

    let idList = [];
    if (result.length > 0) {
      result.map((i) => {
        idList.push(i.collectionId);
      });
    }

    this.props.actions.action.claimRewards({idList});
  };

  /**
   * 退出游戏
   */
  handleGameOver = () => {
    // 退出首页
    Taro.navigateBack();
  };

  /**
   * 渲染
   * @returns
   */
  render() {
    let {
      main: {gameLotteries},
      visible,
      actions: {action},
    } = this.props;
    const {OPERATES, atModal} = this.state;
    // 抓不到娃娃和金币是操作再来一次和退出游戏
    let operates = [];
    if (gameLotteries.length == 1) {
      if (gameLotteries[0].prizeType == GAME_RPICE_TYPE['gold']) {
        operates = [OPERATES[0], OPERATES[1]];
      } else {
        operates = [OPERATES[1], OPERATES[2]];
      }
    } else if (gameLotteries.length == 0) {
      operates = [OPERATES[0], OPERATES[1]];
    } else {
      operates = [OPERATES[1], OPERATES[2]];
    }

    let resultMore = gameLotteries.length > 5 ? true : false;
    console.log('resultmORE', resultMore);

    return (
      <AtModal isOpened={visible} className="resultModal" closeOnClickOverlay={atModal.closeOnClickOverlay}>
        <AtModalContent>
          <View className={classNames('modalContent', 'singleModalContent')}>
            <View className="resultTitle"></View>
            <View className="result">
              {gameLotteries.length > 0 ? this.renderPrizeItems(gameLotteries) : this.renderResultEmpty(resultMore)}
            </View>
          </View>
          <View className="modalFooter">
            {operates.map((i: any, index: number) => (
              <Button
                className={
                  i.label == '再来一次'
                    ? operates.findIndex((op) => op.label == '退出游戏') > -1
                      ? 'right'
                      : 'left'
                    : i.className
                }
                onClick={() => this[i.func](i)}
                key={'result' + index}
              >
                {i.label}
              </Button>
            ))}
          </View>
        </AtModalContent>
      </AtModal>
    );
  }

  /**
   * 渲染成功
   * @returns
   */
  renderPrizeItems(items) {
    const {badge} = this.state;

    return (
      <View className="successResult">
        <View className="title">恭喜您获得</View>
        <View className="prizes">
          {items.map((i: any, index: number) =>
            i.count ? (
              <View className="item" key={index}>
                <AtBadge value={i.count} maxValue={badge.max} key={'prize' + index}>
                  <Image
                    src={i.img ? i.img : RESULT_TYPE[i.prizeType].thum}
                    className={RESULT_TYPE[i.prizeType].className}
                    mode="aspectFill"
                  />
                </AtBadge>
              </View>
            ) : (
              this.renderItemContent(i)
            ),
          )}
        </View>
        <View className="extraTitle">去查看奖励吧~</View>
      </View>
    );
  }

  /**
   * 渲染内容
   * @param i
   * @returns
   */
  renderItemContent(i) {
    return (
      <View className="item">
        <Image
          src={i.img ? i.img : RESULT_TYPE[i.prizeType].thum || IMAGE_EMPTY}
          className={RESULT_TYPE[i.prizeType].className}
          mode="aspectFill"
        />
      </View>
    );
  }

  /**
   * 渲染为空的情况
   * @returns
   */
  renderResultEmpty(more) {
    return <View className="failResult">什么都没有抓到&nbsp;再接再励吧</View>;
  }
}
